package com.lark.algorithm.train.onChapter.linkedList;

/**
 * @author btmood
 * @version 1.0
 * @apiNote
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 *
 *
 *
 * 示例 1：
 *
 *
 * 输入：head = [1,2,3,4,5], n = 2
 * 输出：[1,2,3,5]
 * 示例 2：
 *
 * 输入：head = [1], n = 1
 * 输出：[]
 * 示例 3：
 *
 * 输入：head = [1,2], n = 1
 * 输出：[1]
 *
 *
 * 提示：
 *
 * 链表中结点的数目为 sz
 * 1 <= sz <= 30
 * 0 <= Node.val <= 100
 * 1 <= n <= sz
 * @since 2024-05-22 11:35
 */
public class D20240522Q19_删除链表的倒数第N个结点 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode dummyHead = new ListNode(-1, head);
        ListNode fast = dummyHead;
        ListNode slow = dummyHead;
        while (n != 0) {
            fast = fast.next;
            n--;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        ListNode nextNode = slow.next.next;
        slow.next.next = null;
        slow.next = nextNode;
        return dummyHead.next;
    }

    /**
     * 疑问：递归删除链表节点时，虚拟头节点怎么设置？
     * 删除以head为头节点的链表中倒数第n个节点
     * 返回新的头节点
     * @param head
     * @param n
     * @return
     */
    int count = 0;
    public ListNode removeNthFromEnd2(ListNode head, int n) {
        if (head == null) {
            return head;
        }
        head.next = removeNthFromEnd2(head.next, n);
        count++;
        return n == count ? head.next : head;
    }

    public static class ListNode {
        int val;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
        ListNode next;
    }
}
